<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浏览历史</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            background-color: #fff9e6;
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            background: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .back-btn {
            padding: 8px 16px;
            background-color: #ffd700;
            color: #333;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .back-btn:hover {
            background-color: #ffed4a;
            transform: translateY(-1px);
        }

        .clear-btn {
            padding: 8px 16px;
            background-color: #ff6b6b;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .clear-btn:hover {
            background-color: #ff5252;
            transform: translateY(-1px);
        }

        .history-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
        }

        .history-item {
            position: relative;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: box-shadow 0.3s ease;
        }

        .history-item:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .history-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px 8px 0 0;
            transition: transform 0.3s ease;
        }

        .history-item:hover .history-image {
            transform: scale(1.05);
        }

        .history-info {
            padding: 15px;
        }

        .history-name {
            font-size: 16px;
            margin-bottom: 10px;
            color: #333;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .history-price {
            color: #ff4400;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .history-time {
            color: #999;
            font-size: 12px;
        }

        .history-type {
            position: absolute;
            top: 10px;
            left: 10px;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: white;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 24px;
            height: 24px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .history-item:hover .delete-btn {
            opacity: 1;
        }

        .delete-btn i {
            color: #ff4400;
            font-size: 12px;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .empty-state i {
            font-size: 48px;
            color: #ddd;
            margin-bottom: 20px;
        }

        .load-more {
            text-align: center;
            margin-top: 20px;
        }

        .load-more-btn {
            padding: 10px 20px;
            background-color: #ffd700;
            color: #333;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .load-more-btn:hover {
            background-color: #ffed4a;
            transform: translateY(-1px);
        }

        .load-more-btn:disabled {
            background-color: #ddd;
            cursor: not-allowed;
            transform: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <button class="back-btn" onclick="location.href='mine.html'">
                <i class="fas fa-arrow-left"></i> 返回
            </button>
            <button class="clear-btn" onclick="clearHistory()">
                <i class="fas fa-trash-alt"></i> 清空历史
            </button>
        </div>

        <div class="history-list" id="historyList">
            <!-- 历史记录将通过JavaScript动态加载 -->
        </div>

        <div class="load-more">
            <button class="load-more-btn" id="loadMoreBtn" onclick="loadMore()">
                加载更多
            </button>
        </div>
    </div>

    <script>
        let currentPage = 0;
        const pageSize = 20;
        let hasMore = true;

        // 加载历史记录
        function loadHistory(page = 0) {
            $.ajax({
                url: '/history/list',
                type: 'GET',
                data: {
                    page: page,
                    limit: pageSize
                },
                success: function(response) {
                    console.log('Response:', response);
                    if (response.state === 1) {
                        if (page === 0) {
                            $('#historyList').empty();
                        }
                        
                        // 获取历史记录数据
                        const histories = response.data.data || [];
                        console.log('Histories:', histories);
                        
                        // 使用 Set 来去重，基于 productId 和 isAuction 组合
                        const uniqueHistories = [];
                        const seen = new Set();
                        
                        histories.forEach(history => {
                            const key = `${history.productId}-${history.isAuction}`;
                            if (!seen.has(key)) {
                                seen.add(key);
                                uniqueHistories.push(history);
                            }
                        });
                        
                        if (uniqueHistories.length < pageSize) {
                            hasMore = false;
                            $('#loadMoreBtn').prop('disabled', true);
                        }

                        if (uniqueHistories.length === 0 && page === 0) {
                            showEmptyState();
                            return;
                        }

                        uniqueHistories.forEach(history => {
                            try {
                                const historyHtml = `
                                    <div class="history-item" onclick="viewProduct(${history.productId}, ${history.isAuction}, ${history.auctionId})">
                                        <div class="history-type">${history.isAuction ? '拍卖' : '闲置'}</div>
                                        <div class="delete-btn" onclick="event.stopPropagation(); deleteHistory(${history.id})">
                                            <i class="fas fa-times"></i>
                                        </div>
                                        <img src="${history.productImage || 'img/placeholder-product.png'}" class="history-image" 
                                             alt="${history.productName || '未知商品'}"
                                             onerror="this.src='img/placeholder-product.png';">
                                        <div class="history-info">
                                            <div class="history-name">${history.productName || '未知商品'}</div>
                                            <div class="history-price">¥${(history.productPrice || 0).toFixed(2)}</div>
                                            <div class="history-time">浏览时间：${history.viewTime ? new Date(history.viewTime).toLocaleString() : '未知时间'}</div>
                                        </div>
                                    </div>
                                `;
                                $('#historyList').append(historyHtml);
                            } catch (error) {
                                console.error('Error rendering history item:', error, history);
                            }
                        });
                    } else {
                        console.error('Response error:', response.msg);
                        if (page === 0) {
                            showEmptyState();
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Ajax error:', {xhr, status, error});
                    if (page === 0) {
                        showEmptyState();
                    }
                }
            });
        }

        // 显示空状态
        function showEmptyState() {
            $('#historyList').html(`
                <div class="empty-state">
                    <i class="fas fa-history"></i>
                    <p>暂无浏览记录</p>
                </div>
            `);
            $('#loadMoreBtn').hide();
        }

        // 加载更多
        function loadMore() {
            if (!hasMore) return;
            currentPage++;
            loadHistory(currentPage);
        }

        // 删除单条历史记录
        function deleteHistory(id) {
            if (!confirm('确定要删除这条浏览记录吗？')) {
                return;
            }

            $.ajax({
                url: `/history/delete/${id}`,
                type: 'DELETE',
                success: function(response) {
                    if (response.state === 1) {
                        currentPage = 0;
                        hasMore = true;
                        $('#loadMoreBtn').prop('disabled', false).show();
                        loadHistory();
                    } else {
                        alert(response.msg || '删除失败');
                    }
                }
            });
        }

        // 清空历史记录
        function clearHistory() {
            if (!confirm('确定要清空所有浏览记录吗？')) {
                return;
            }

            $.ajax({
                url: '/history/clear',
                type: 'DELETE',
                success: function(response) {
                    if (response.state === 1) {
                        showEmptyState();
                    } else {
                        alert(response.msg || '清空失败');
                    }
                }
            });
        }

        // 查看商品详情
        function viewProduct(productId, isAuction, auctionId) {
            if (isAuction) {
                window.location.href = `auction-detail.html?id=${auctionId}`;
            } else {
                window.location.href = `product-detail.html?id=${productId}`;
            }
        }

        // 页面加载完成后执行
        $(document).ready(function() {
            loadHistory();
        });
    </script>
</body>
</html> 